package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.cmn.client.DictFeignClient;
import com.atguigu.yygh.common.handler.YyghException;
import com.atguigu.yygh.enums.DictEnum;
import com.atguigu.yygh.hosp.repository.HospitalRepository;
import com.atguigu.yygh.hosp.service.DepartmentService;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.model.hosp.BookingRule;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.vo.hosp.BookingScheduleRuleVo;
import com.atguigu.yygh.vo.hosp.HospitalQueryVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class HospitalServiceImpl implements HospitalService {

    @Autowired
    private HospitalRepository hospitalRepository;
    //注入远程调用接口
    @Autowired
    private DictFeignClient dictFeignClient;
    @Autowired
    private MongoTemplate mongoTemplate;
  /*  @Autowired
    private HospitalService hospitalService;
    @Autowired
    private DepartmentService departmentService;*/


    //上传保存医院
    @Override
    public void save(Map<String, Object> paramMap) {
        //封装参数数据
        //把map转换成json
        String jsonString = JSONObject.toJSONString(paramMap);
        //把json转换成对象
        Hospital hospital = JSONObject.parseObject(jsonString, Hospital.class);

        //save和insert方法 在没有该数据时没有什么区别 但是save在改数据时 会更新改数据
        //判断医院信息是否存在
       Hospital targetHospital= hospitalRepository.getHospitalByHoscode(hospital.getHoscode());
       if(targetHospital!=null){
           //更新操作
           hospital.setStatus(targetHospital.getStatus());
           hospital.setCreateTime(targetHospital.getCreateTime());
           hospital.setUpdateTime(new Date());
           hospital.setIsDeleted(0);
           hospital.setId(targetHospital.getId());
           hospitalRepository.save(hospital);
       }else{
           //没有次医院信息 进行新增操作
           //0：未上线 1：已上线
           hospital.setStatus(0);
           hospital.setCreateTime(new Date());
           hospital.setUpdateTime(new Date());
           hospital.setIsDeleted(0);
           hospitalRepository.save(hospital);


       }


    }

    //查询医院信息
    @Override
    public Hospital getByHoscode(String hoscode) {
        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);

        return hospital;
    }

    //带条件 分页查询医院接口
    @Override
    public Page<Hospital> selectPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
      /*  //创建排序对象
        Sort sort=Sort.by(Sort.Direction.DESC,"createTime");
        //设置分页对象 ,0是第一页
        Pageable pageable= PageRequest.of(page-1,limit,sort);
        //设置查询条件
        Hospital hospital=new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo,hospital);
        //设置查询规则
        ExampleMatcher matcher=ExampleMatcher.matching()//构建对象
        .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)//改变默认字符
        .withIgnoreCase(true);
        //创建实例模板
        Example<Hospital> example=Example.of(hospital,matcher);

        Page<Hospital> hospitalPage=hospitalRepository.findAll(example,pageable);*/

      //设置排序对象
        Sort sort=Sort.by(Sort.Direction.DESC,"createTime");

      //设置分页对象(0是第一页)
        Pageable pageable = PageRequest.of(page - 1, limit, sort);

        //设置查询条件
        Hospital hospital=new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo,hospital);

        //设置查询规则
        ExampleMatcher matcher = ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).withIgnoreCase(true);

        //创建实例模板
        Example<Hospital> example=Example.of(hospital,matcher);

        Page<Hospital> hospitalPage=hospitalRepository.findAll(example,pageable);

        //跨模块调用  查询字典服务 翻译编码信息
        //遍历封装医院等级数据、地址等相关信息
        hospitalPage.getContent().stream().forEach(item->{
            this.packHospital(item);
        });

        return hospitalPage;

    }

    //更新上线状态
    @Override
    public void updateStatus(String id, Integer status) {
        if(status.intValue() == 0 || status.intValue() == 1) {
            //根据id查询
            Hospital hospital = hospitalRepository.findById(id).get();
            //更新属性。更新时间
            hospital.setUpdateTime(new Date());
            hospital.setStatus(status);
            hospitalRepository.save(hospital);
        }
    }
    //获取医院详情
    @Override
    public Map<String, Object> getHospInfoById(String id) {
        Map<String,Object> map=new HashMap();
        //根据id查询数据（字段编码翻译）
        Hospital hospital = this.packHospital(hospitalRepository.findById(id).get());
        //将信息封装到map中
        map.put("hospital", hospital);
        map.put("bookingRule",hospital.getBookingRule());
        //不需要重复返回
        hospital.setBookingRule(null);
        return map;

    }
    //根据医院编码 获取医院名称
    @Override
    public String getHospName(String hoscode) {
        Hospital hospital = this.getByHoscode(hoscode);
        if(hospital!=null){
            return hospital.getHosname();
        }
        return "";
    }

    //根据医院名称获取医院列表
    @Override
    public List<Hospital> findByHosname(String hosname) {
        List<Hospital> list =
                hospitalRepository.getHospitalByHosnameLike(hosname);
        return list;
    }

    @Override
    public Map<String, Object> item(String hoscode) {
        Map<String, Object> result = new HashMap<>();
        //根据hoscode查询医院信息
        Hospital hospital = this.packHospital(
                hospitalRepository.getHospitalByHoscode(hoscode)) ;
        //封装医院基本信息
        result.put("hospital",hospital);
        //封装预约规则
        result.put("bookingRule",hospital.getBookingRule());
        //清除重复数据
        hospital.setBookingRule(null);
        return result;

    }

    //翻译字段编码信息
    private Hospital packHospital(Hospital hospital) {

        String hostypeString = dictFeignClient.getName(DictEnum.HOSTYPE.getDictCode(),hospital.getHostype());
        String provinceString = dictFeignClient.getName(hospital.getProvinceCode());
        String cityString = dictFeignClient.getName(hospital.getCityCode());
        String districtString = dictFeignClient.getName(hospital.getDistrictCode());

        hospital.getParam().put("hostypeString", hostypeString);
        hospital.getParam().put("fullAddress", provinceString + cityString + districtString + hospital.getAddress());
        return hospital;

    }


}
